﻿using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Net;
using NLog;

namespace SS.Form.Core
{
    public class SendSmsHelper
    {
        static readonly Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        public static void SendSms(string telPhone, string content)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            string url = "https://172.17.40.164/rest-service/1607919185428512/1607922410848288";
            string json = "{ \"msgAccount\": \"cfc3c33f65b34323910aa70335f373b8\", \"msgKey\": \"05d813658bea7b0bd502b20b6d9d274af35f69e373d436451058f35865e63ee0\", \"content\": \""+content+"\", \"phone\": \""+telPhone+"\"}";
            string certificatePath =System.Web.HttpContext.Current.Server.MapPath("~/client.pkcs12") ;
            string certificatePassword = "HhsP2sSKdPqW1Vg5tgsEgQ==";
            var re= PostJsonAsync2(url, json,certificatePath, certificatePassword);
            Logger.Info("re:"+re);

        }

        public  static string PostJsonAsync2(string url, string json, string certificatePath, string certificatePassword)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            System.Net.ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
            var handler = new WebRequestHandler();
            handler.ClientCertificateOptions = ClientCertificateOption.Manual;
            //handler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;

            // 加载证书，这里假设证书已经存在于你的机器上
            var certificate = new X509Certificate2(certificatePath, certificatePassword, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
            handler.ClientCertificates.Add(certificate);
            handler.ServerCertificateValidationCallback = CheckValidationResult;
            //handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
            HttpClient hhttpClient = new HttpClient(handler);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            hhttpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            try
            {
                var response =  hhttpClient.PostAsync(url, content).Result;;
                string resultContent = response.Content.ReadAsStringAsync().Result;
                return resultContent;
            }
            catch (HttpRequestException e)
            {
                //Console.WriteLine("\nException Caught!");
                //Console.WriteLine("Message :{0} ", e.Message);
                Logger.Info("ex:"+e.Message);
                return String.Empty;
            }
        }

        public static string PostJsonAsync(string url, string json, string certificatePath, string certificatePassword)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidate;
            Uri uri = new Uri(@url);
            HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;
            byte[] bs = Encoding.UTF8.GetBytes(json);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = bs.Length;
            request.GetRequestStream().Write(bs, 0, bs.Length);
            try
            {
                InstallCertificate(certificatePath, certificatePassword, StoreLocation.CurrentUser, StoreName.My);
                X509Certificate cer = new X509Certificate(certificatePath, certificatePassword);
                request.ClientCertificates.Add(cer);
                request.KeepAlive = false;
                request.ProtocolVersion = HttpVersion.Version10;
                request.Proxy = null;
                //request.UserAgent = DefaultUserAgent;
                using (Stream reqStram = request.GetRequestStream())
                {
                    reqStram.Write(bs, 0, bs.Length);
                    reqStram.Close();
                }

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                Logger.Info("ex:"+ex.Message);
            }
            return String.Empty;
        }

        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }
        private static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
        {
            // trust any certificate!!!
            //System.Console.WriteLine("Warning, trust any certificate");
            //为了通过证书验证，总是返回true
            return true;
        }
        public static bool InstallCertificate(string certFilePath, string password, StoreLocation location, StoreName storeName)
        {
            try
            {
                if (!File.Exists(certFilePath))
                {
                    return false;
                }
                byte[] certData = File.ReadAllBytes(certFilePath);
                X509Certificate2 cert = new X509Certificate2(certData, password, X509KeyStorageFlags.Exportable);
                X509Store store = new X509Store(storeName, location);
                store.Open(OpenFlags.MaxAllowed);
                store.Remove(cert);
                store.Add(cert);
                store.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
